package com.specificgroup.jira.plugin.acpro.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Ivan Holub
 */
public class HttpUtil {

    public static String post(String url, String request) throws IOException {
        PostMethod post = new PostMethod(url);
        post.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8"));
        post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
        HttpClient httpclient = new HttpClient();
        try {
            int result = httpclient.executeMethod(post);
            InputStream is = post.getResponseBodyAsStream();
            try {
                String retValue = IOUtils.toString(is, "UTF-8");
                retValue = removeNotValidXmlCharacters(retValue);
                return retValue;
            } finally {
                IOUtils.closeQuietly(is);
            }
        } finally {
            post.releaseConnection();
        }
    }

    private static String removeNotValidXmlCharacters(String in) {
        StringBuilder sb = new StringBuilder();
        char current;
        for (int i = 0; i < in.length(); i++) {
            current = in.charAt(i);
            if (!((current == 0x1b) || (current == 0x1d))) {
                sb.append(current);
            }
        }
        return sb.toString();
    }

}
